package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.core.view.isVisible
import com.blankj.utilcode.util.ThreadUtils
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.Base64Util
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.FileUtil
import com.gexiaobao.pigeon.app.util.MeSandboxFileEngine
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.ActivityApplyPigeonCarrierBinding
import com.gexiaobao.pigeon.ui.activity.ActivityMapLocation
import com.gexiaobao.pigeon.viewmodel.DrippingViewModel
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import com.zs.easy.imgcompress.util.GBMBKBUtil
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import me.hgj.jetpackmvvm.util.startActivityForResult
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.net.URLEncoder

/**
 * @Author      : hxw
 * @Date        : 2024/6/19 17:11
 * @Describe    : 申请接鸽员
 */
class ActivityApplyPigeonCarrier : BaseActivity<DrippingViewModel, ActivityApplyPigeonCarrierBinding>() {

    private var mLatitude: Double = 0.0
    private var mLongitude: Double = 0.0
    private var idCardFrontFile: File? = null
    private var idCardBackFile: File? = null
    private var driverFile: File? = null
    private var mProCityArea = ""
    private var mAddress = ""
    private var orgId = 0

    private val HTTP_CLIENT = OkHttpClient().newBuilder().build()
    private var idCardNumberTypeFront = 0

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "申请接鸽员"

        orgId = intent.getIntExtra("orgId", 0)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.ivIdCardFront,
            mDatabind.ivIdCardBack,
            mDatabind.llMapLocation,
            mDatabind.tvNext,
            mDatabind.ivDriverLicense
        ) { it ->
            when (it) {
                mDatabind.tvNext -> {
                    nextSubmitCarInfo()
                }

                mDatabind.llMapLocation -> {
                    startActivityForResult<ActivityMapLocation> {
                        if (it != null) {
                            val mName = it.getStringExtra("name").toString()
                            mAddress = it.getStringExtra("address").toString()
                            mDatabind.tvDrippingAddress.text = mAddress
                            mLatitude = it.getDoubleExtra("latitude", 0.0)
                            mLongitude = it.getDoubleExtra("longitude", 0.0)
                            mProCityArea = it.getStringExtra("proCityArea").toString()
                            LogUtils.debugInfo("$mName--$mAddress--${mLatitude.toString()}--$mLongitude")
                        }
                    }
                }

                mDatabind.includeBar.ivBack -> {
                    finish()
                }

                mDatabind.ivIdCardFront -> {
                    selectHeadIcon("front")
                }

                mDatabind.ivIdCardBack -> {
                    selectHeadIcon("back")
                }

                mDatabind.ivDriverLicense -> {
                    selectHeadIcon("driver")
                }

            }
        }
    }

    private fun nextSubmitCarInfo() {
        val mobileNumber = mDatabind.etContactMobile.text.toString().trim()
        val contactName = mDatabind.etContactName.text.toString().trim()
        when {
            mDatabind.tvDrippingAddress.text.toString().trim().isEmpty() -> RxToast.warning("未选择联系地址")
            contactName.isEmpty() -> RxToast.warning("填写联系人姓名")
            mobileNumber.isEmpty() -> RxToast.warning("填写联系人电话")
            mobileNumber.isNotEmpty() && !Util.isTelPhoneNumber(mobileNumber) -> RxToast.warning("手机号格式有误")
            idCardFrontFile == null -> RxToast.warning("未上传身份证正面照")
            idCardBackFile == null -> RxToast.warning("未上传身份证背面照")
            driverFile == null -> RxToast.warning("未上传驾驶证")
            idCardNumberTypeFront == -1 -> showMessage("请上传有效身份证件")
            else -> {
                val map = mapOf(
                    "name" to contactName,
                    "mobile" to mobileNumber,
                    "lon" to mLongitude,
                    "lat" to mLatitude,
                    "provinceCity" to mProCityArea,
                    "address" to mAddress,
                    "identityCardObverse" to idCardFrontFile,
                    "identityCardReverse" to idCardBackFile,
                    "drivingCard" to driverFile,
                    "identityCard" to mDatabind.tvIDCardNumber.text.toString()
                )
                showLoading(getString(R.string.loading))
                mViewModel.addTransporterApplyBase(map)
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.addTransporterResult.observe(this) {
            startActivity<ActivityAddCarInfo>("orgId" to orgId, "baseInfoId" to it.id,"type" to "ActivityApplyPigeonCarrier")
            finish()
        }
    }

    private fun selectHeadIcon(type: String) {
        val selectionModel: PictureSelectionModel = PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(PictureUtil.getCompressFileEngine())
            .setSandboxFileEngine(MeSandboxFileEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .setQueryFilterListener { false }
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(false)
            .isPreviewImage(true)
            .isMaxSelectEnabledMask(true)
            .isDirectReturnSingle(true)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                val path = result!![0].realPath
                val bitmap = BitmapFactory.decodeFile(path)
                compressedPicture(path, type)
                when (type) {
                    "front" -> {
                        idCard(path)
                        mDatabind.ivIdCardFront.setImageBitmap(bitmap)
                    }

                    "driver" -> {
                        mDatabind.ivDriverLicense.setImageBitmap(bitmap)
                    }

                    else -> {
                        mDatabind.ivIdCardBack.setImageBitmap(bitmap)

                    }
                }
            }

            override fun onCancel() {}
        })
    }

    private fun idCard(path: String?) {
        val mIdCardType = "back"
        ThreadUtils.runOnUiThread {
            showLoading("识别中...")
        }
        Thread {
            val mediaType: MediaType = "application/x-www-form-urlencoded".toMediaTypeOrNull()!!
            // image 可以通过 getFileContentAsBase64("C:\fakepath\微信图片_20230809113403.jpg") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
            val body = ("id_card_side=$mIdCardType&image=" + URLEncoder.encode(
                Base64Util.encode(FileUtil.readFileByBytes(path)), "UTF-8"
            ) + "&url=https%3A%2F%2Faip.baidubce.com%2Frest%2F2.0%2Focr%2Fv1%2Fidcard&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false"
                    ).toRequestBody(mediaType)
            val request = Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + getAccessToken())//Constant.ACCESS_TOKEN
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build()
            val response = HTTP_CLIENT.newCall(request).execute()
            ThreadUtils.runOnUiThread {
                dismissLoading()
            }
            setCardInfo(response.body?.string())
        }.start()
    }

    private fun setCardInfo(data: String?) {
        try {
            ThreadUtils.runOnUiThread {
                if (JSONObject(data.toString()).has("error_code")) {
                    if (JSONObject(data.toString()).getInt("error_code") == 111) {
                        RxToast.showToast("令牌过期")
                        return@runOnUiThread
                    }
                }
                if (JSONObject(data.toString()).has("idcard_number_type")) {
                    idCardNumberTypeFront = JSONObject(data.toString()).getInt("idcard_number_type")
                    if (idCardNumberTypeFront == -1) {
                        RxToast.warning("识别失败，请重新上传")
                        return@runOnUiThread
                    }
                }
                idCardNumberTypeFront = 1
                val idCardNum: JSONObject?
                val wordResult = data?.let { JSONObject(it).getJSONObject("words_result") }
                if (wordResult != null) {
                    if (wordResult.has("公民身份号码")) {
                        idCardNum = wordResult.getJSONObject("公民身份号码")
                        if (idCardNum != null) {
                            val wordIdNUm = idCardNum.getString("words")
                            mDatabind.tvIDCardNumber.text = wordIdNUm
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @Throws(IOException::class)
    private fun getAccessToken(): String? {
        val mediaType = "application/x-www-form-urlencoded".toMediaTypeOrNull()
        val body = ("grant_type=client_credentials&client_id=" + Constant.API_KEY
                + "&client_secret=" + Constant.SECRET_KEY
                ).toRequestBody(mediaType)
        val request: Request = Request.Builder()
            .url("https://aip.baidubce.com/oauth/2.0/token")
            .method("POST", body)
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .build()
        val response = HTTP_CLIENT.newCall(request).execute()
        return JSONObject(response.body!!.string()).getString("access_token")
    }

    private fun compressedPicture(path: String, type: String) {
        /** 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200） */
        EasyImgCompress.withSinglePic(this@ActivityApplyPigeonCarrier, path)
            .maxPx(1200)
            .maxSize(1024)
            .enableLog(true)
            .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                override fun onStart() {
                    LogUtils.debugInfo("onStart")
                }

                override fun onSuccess(file: File) {
                    when (type) {
                        "front" -> {
                            idCardFrontFile = file
                        }

                        "driver" -> {
                            driverFile = file
                        }

                        else -> {
                            idCardBackFile = file
                        }
                    }
                    LogUtils.debugInfo("onSuccess size = " + GBMBKBUtil.getSize(file.length()) + " getAbsolutePath= " + file.absolutePath)
                }

                override fun onError(error: String) {
                    LogUtils.warnInfo("onError error = $error")
                }
            }).start()
    }
}